import { DataType } from "./type";
import type { VarDeclare } from "../data/var_declare";
import type { IDeserializable } from "~/models/serialize/IDeserializable";
import { Deserializer } from "~/models/serialize/Deserializer";
import { Dzer } from "~/models/serialize";

// 定义: 接口类型 (和类型)：
// 不是一种具体的类型，而是类型的类型。在这里定义结构和生成器

export class InterfaceType extends DataType implements IDeserializable {

  className: string = 'InterfaceType'

  constructor(
    public name: string,
    public members: VarDeclare[] = []
  ) {
    super()
  }

  get default(): any {
    const v = {} as any
    this.members.forEach(m => {
      v[m.name] = m.type.default
    })
    return v
  }

  // 和类型能接受成员类型列表相同的
  // 注意！：为防止类型意义的错误解释。成员类型需要相同，而不是兼容
  // 否则 rect(x, y, w, h)和rect(l, r, b, t)将会混淆！
  receiveType(t: DataType): boolean {
    // 同一类型则跳过后续判断
    if (t.name === this.name) {
      return true;
    }

    // 只能够接受其他和类型
    if ((t as any).members === undefined) {
      return false;
    }
    const _t = t as InterfaceType;

    // 本接口的成员必须在t中都找到
    const tMember = _t.members.map(x => x.name);
    return this.members.every(m => tMember.includes(m.name));
  }

  override receiveValue(t: any): boolean {
    return this.members.every(member => {
      return t && member.type.receiveValue(t[member.name])
    })
  }
}

